import com.github.eprendre.tingshu.utils.Episode
import com.github.kittinunf.fuel.Fuel
import com.github.kittinunf.fuel.json.responseJson
import org.jsoup.Jsoup
import org.junit.Test

class XBaiduTest {

    @Test
    fun bookDetail() {
//        val url = "https://m.bilibili.com/video/BV1W54y1C7jc"
//        val url = "https://m.bilibili.com/video/BV1Jf4y1C7m8"
        val url = "https://m.bilibili.com/video/BV1Ft411W7Wp"
        val doc = Jsoup.connect(url).testConfig(false).get()
        val elements = doc.select(".m-video-part-new > ul > li")
        val episodes = ArrayList<Episode>()
        if (elements.isEmpty()) {
            episodes.add(Episode("1p", url))
        } else {
            elements.forEachIndexed { index, element ->
                val title = element.text()
                val page = index + 1
                episodes.add(Episode(title, "$url?p=$page"))
            }
        }

        episodes.take(5).forEach {
            println(it)
        }
        assert(episodes.size > 0)
    }

    @Test
    fun getBookDetailInfo() {
        val bookUrl = "/Story/0归档/D东北往事之黑道风云20年(完结197)_孔二狗_周建龙"
        val list = _getAudioList(bookUrl)
        list.sortedBy { it.title }
        list.forEach { println(it.title)}
    }

    fun _getAudioList(folder: String): List<Episode> {
        val accessToken = "123.4c5739efe2c3b2ec026077ec63e3b669.YQrh2TV23aEw4QwINRTlkAu5GZjEpc3m4GYSqn8.GtuUUA"
        val dataUrl =
            "https://pan.baidu.com/rest/2.0/xpan/file?method=list&access_token=${accessToken}&dir=${folder}&order=name&limit=100000&web=web&showempty=0"
        val data = Fuel.get(dataUrl).responseJson().third.get().obj().getJSONArray("list")
        val list = mutableListOf<Episode>()
        run loop@{
            (0 until data.length()).forEach {
                val result = data.getJSONObject(it)
                val isDir = result.getInt("isdir")
                val path = result.getString("path")
                val category = result.getInt("category")
                if (isDir == 1) {
                    list.addAll(_getAudioList(path))
                } else if (category == 2) {
                    val title = result.getString("server_filename")
                    val fsid = result.getLong("fs_id")
                    list.add(
                        Episode(title, fsid.toString())
                    )

                }
            }
        }

        return list
    }
}